<template>
    <div>
        <bk-fixed-navbar v-if="nav.show"
            :position="nav.position"
            :nav-items="nav.items"></bk-fixed-navbar>
        <!-- <input name="file" type="file" accept="image/png,image/gif,image/jpeg" @change="update" /> -->
        <!-- <section>
            <bk-select searchable v-model="value" @toggle="handleToggle">
                <bk-option v-for="category in categorys"
                    :key="category.id"
                    v-bind="category">
                    <div class="select-collection" @mouseenter="handleMouseEnter(category.id)" @mouseleave="handleMouseLeave(category.id)">
                        <span>{{ category.name }}</span>
                    </div>
                </bk-option>
            </bk-select>
        </section> -->
        <el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-form">
            <el-form-item label="商品名称" prop="name" style="width:50%">
                <el-input v-model="form.name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="price" style="width:50%">
                <el-input v-model.number="form.price"></el-input>
            </el-form-item>
            <el-form-item label="商品库存" prop="repertory_number" style="width:50%">
                <el-input v-model.number="form.repertory_number"></el-input>
            </el-form-item>
            <el-form-item label="商品描述" prop="commoditydescribe" style="width:50%">
                <el-input type="textarea" v-model="form.commoditydescribe"></el-input>
            </el-form-item>
            <el-form-item label="商品类型" prop="category_id">
                <el-select v-model="form.category_id" placeholder="请选择商品类型">
                    <el-option
                        v-for="item in categoryList"
                        :key="item.id"
                        :label="item.category"
                        :value="item.id">
                    </el-option>
                </el-select>
                <category-manage :key="componentKey" :categorys="categoryList" @updateCategory="updateCategory">商品类别管理</category-manage>
            </el-form-item>
            <el-form-item v-if="isAdd" label="上传图片" ref="uploadElement" prop="picture">
                <el-input v-model="ruleForm.picture" v-if="false"></el-input>
                <el-upload
                    class="avatar-uploader"
                    ref="upload"
                    :show-file-list="false"
                    action="/index/upload"
                    :before-upload="beforeUpload"
                    :on-change="handleChange"
                    :auto-upload="false"
                    :data="form">
                    <img v-if="form.picture" :src="form.picture" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button v-if="isAdd" type="primary" @click="submitForm('form')">创建</el-button>
                <el-button v-else type="primary" @click="submitForm('form')">修改</el-button>
                <el-button @click="resetForm('form')">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>
<script>
    import categoryManage from '../../../components/category/categoryManage.vue'
    export default {
        components: {
            categoryManage
        },
        data () {
            return {
                nav: {
                    show: false,
                    position: 'middle',
                    items: [
                        {
                            icon: 'icon-weixin-shape',
                            text: '商品',
                            tooltip: '回到商品页',
                            action: () => {
                                this.$router.push({ name: 'commodity' })
                            }
                        }
                    ]
                },
                config: {
                    theme: 'success',
                    message: ''
                },
                isAdd: true,
                form: {
                    name: '',
                    price: null,
                    category_id: null,
                    repertory_number: null,
                    commoditydescribe: null,
                    picture: null
                },
                file: null,
                componentKey: 0,
                value: 1,
                categoryList: [
                ],
                hoverId: -1,
                rules: {
                    name: [
                        {
                            required: true,
                            message: '请输入商品名称',
                            trigger: 'blur'
                        }
                    ],
                    price: [
                        {
                            required: true,
                            message: '请输入商品价格',
                            trigger: 'blur'
                        },
                        { type: 'number', message: '商品价格必须为数字值' }
                    ],
                    repertory_number: [
                        {
                            required: true,
                            message: '请输入商品价格',
                            trigger: 'blur'
                        },
                        { type: 'number', message: '商品库存必须为数字值' }
                    ],
                    category_id: [
                        {
                            required: true,
                            message: '请选择商品类型',
                            trigger: 'blur'
                        }
                    ],
                    picture: [
                        {
                            required: true,
                            message: '请选择商品图片',
                            trigger: 'blur'
                        }
                    ]
                },
                alterData: [],
                url: ''
            }
        },
        created () {
            this.getCategory()
            if ((typeof this.$route.params.alterData !== 'undefined')) {
                this.alterData = this.$route.params.alterData
                this.form.name = this.alterData.name
                this.form.price = this.alterData.price
                this.form.category_id = this.alterData.category_id
                this.form.repertory_number = this.alterData.repertory_number
                this.form.picture = this.alterData.picture
                this.form.commoditydescribe = this.alterData.commoditydescribe
                this.isAdd = false
                this.nav.show = true
            }
        },
        methods: {
            updateCategory () {
                this.getCategory()
                this.componentKey = this.componentKey + 1
            },
            async getPicture (imageName) {
                this.$http.get('/image', { params: { 'imageName': imageName }, responseType: 'blob' }).then(res => {
                    const blob = new Blob([res.data])
                    const url = window.URL.createObjectURL(blob)
                    this.form.picture = url
                })
            },
            async getCategory () {
                this.$http.get('/findCommodityCategory').then(res => {
                    this.categoryList = res.data.data
                })
            },
            async addOrAlterCommodity () {
                const param = new FormData()
                param.append('name', this.form.name)
                param.append('picture', this.file)
                param.append('price', this.form.price)
                param.append('category_id', this.form.category_id)
                param.append('repertory_number', this.form.repertory_number)
                param.append('commoditydescribe', this.form.commoditydescribe)
                const config = {
                    headers: { 'Content-Type': 'multipart/form-data' }
                }
                if (this.isAdd) {
                    this.$http.post('/admin/addCommodity', param, config).then(res => {
                        this.config.theme = 'success'
                        this.config.message = '创建成功'
                        this.$bkMessage(this.config)
                        this.$router.push({ name: 'commodity' })
                    })
                } else {
                    const data = {
                        'id': this.alterData.id,
                        'name': this.form.name,
                        'price': this.form.price,
                        'category_id': this.form.category_id,
                        'repertory_number': this.form.repertory_number,
                        'commoditydescribe': this.form.commoditydescribe
                    }
                    this.$http.put('/admin/modifyCommodity', data).then(res => {
                        this.config.theme = 'success'
                        this.config.message = '修改成功'
                        this.$bkMessage(this.config)
                        this.$router.push({ name: 'commodity' })
                    })
                }
            },
            handleMouseEnter (id) {
                this.hoverId = id
            },
            handleMouseLeave () {
                this.hoverId = -1
            },
            handleCollection (option) {
                option.collection = option.collection > 0 ? 0 : 1
            },
            handleToggle () {
                // 收藏置顶
                this.options = this.options.sort((pre, next) => {
                    return next.collection - pre.collection
                })
            },
            testSuccess (file, fileList) {
            },
            testProgress (e, file, fileList) {
                this.update(e)
            },
            testDone () {
            },
            testErr (file, fileList) {
            },
            handleRes (response) {
                if (response.id) {
                    return true
                }
                return false
            },
            submitForm (formName) {
                this.$refs[formName].validate((valid) => {
                    console.log(this.form)
                    if (valid) {
                        this.addOrAlterCommodity()
                    } else {
                        console.log('error submit!!')
                        return false
                    }
                })
            },
            resetForm (formName) {
                this.$refs[formName].resetFields()
            },
            handleChange (file, fileList) {
                this.form.picture = URL.createObjectURL(file.raw)
                this.file = file.raw
            },
            beforeUpload (file) {
                return true
            }
            // update (e) {
            //     console.log(e.target.files[0])
            //     const file = e.target.files[0]
            //     const param = new FormData()
            //     param.append('picture', file)
            //     param.append('price', this.form.price)
            //     param.append('category_id', this.form.category_id)
            //     param.append('repertory_number', this.form.repertory_number)
            //     param.append('commoditydescribe', this.form.commoditydescribe)
            //     const config = {
            //         headers: { 'Content-Type': 'multipart/form-data' }
            //     }
            //     this.$http.post('/admin/addCommodity', param, config).then(res => {
            //         console.log(res)
            //     })
            // }
        }
    }
</script>

<style scoped>
.select-collection {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>
